import Vue from "vue";
import Vuex from "vuex";
import router from "@/router";
import createPersistedState from "vuex-persistedstate"
Vue.use(Vuex);

const store = new Vuex.Store({
  state() {
    return {
      topTabbar: [],
    };
  },
  mutations: {
    updataTopTabbar(state, val) {
      const exists = state.topTabbar.some((item) => item.name === val.name);
      if (!exists) {
        state.topTabbar.push(val);
      }
    },
    reMTopTabbar(state, nameToDelete) {
      const index = state.topTabbar.findIndex((item) => item.name === nameToDelete);
    //   if (index > -1) {
    //     state.topTabbar.splice(index, 1);
    //   }
        let targetRoute;
    if (index > 0) {
        targetRoute =  state.topTabbar[index - 1].name;
    } else if ( state.topTabbar.length > 1) {
        targetRoute =  state.topTabbar[index + 1].name;
    } else {
        targetRoute = '/index';
    }
     state.topTabbar.splice(index, 1);
     router.push(targetRoute);

    },
    resetTopTabbar(state) {
    state.topTabbar = [];
  }
  },
   plugins: [createPersistedState()]
});
export default store;
